<?php

namespace App\Http\Controllers;

use App\Models\Basic;
use App\Models\InviteLog;
use App\Models\LoginLog;
use App\Models\Member;
use App\Models\TaskConfig;
use App\Models\TaskTest;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redis;

class PublicController extends BaseController
{
    /**
	 *	获取微信服务器seesion+openid
	 *	@param $code 小程序获取code值
	 *  return array	
    **/
  	public function getSerSession()
  	{
  	    if(!Input::has('code') || Input::get('code') == '') {
  	        return $this->error('code不存在');
        }

        $input = Input::all();
  	    $code = $input['code'];
        $session = $this->mini_app->auth->session($code);
        if(isset($session['openid']) && isset($session['session_key'])){
            $session_t = $this->_3rd_session();
            try {
                Redis::setex($session_t, 3600*12 ,serialize($session));
            }catch (\Exception $e) {
                return $this->error('缓存session失败');
            }
            $result = [
                '_3rd_session'=>$session_t,
                'user_id' => '',
                'register_flag' => 0     //用户是否注册,0未注册, 1已注册
            ];
            $reg_flag = $this->checkRegister($session['openid']);
            if(empty($reg_flag)) {
                $insert_data = [
                    'openid' => $session['openid'],
                    'name' => $input['name'],
                    'sex' => $input['sex'],
                    'avatar' => $input['avatar'],
                    'session_3rd' => $session_t
                ];
                $res = Member::create($insert_data);
                if($res){
                    $result['user_id'] = $res->id;
                    $result['register_flag'] = 1;
                }else{
                    return $this->error('注册失败');
                }
            }
            if($reg_flag){
                $result['register_flag'] = 1;
                $result['user_id'] = $reg_flag->id;
                //保存session到数据库
                $reg_flag->session_3rd = $session_t;
                $reg_flag->save();
            }
            return $this->success('成功', $result);
        }else{
            return $this->error('获取session失败');
        }
  	}

  	//检车3rd_session是否失效
  	public function checkSession()
    {
        $input = Input::all();
        if(!Redis::exists($input['_3rd_session'])) {

            return $this->error('3rdsession失效');
        }else{

            return $this->success('3rdseesion有效');
        }
    }

    /**
     * 检测用户是否注册
     * @param $openid openid
     * @return bool
     */
  	protected function checkRegister($openid)
    {
        $res = Member::where('openid', $openid)->first();

        return $res ? $res : false;
    }


    /**
     * 获取jssdk配置参数
     * @return \Illuminate\Http\JsonResponse
     */
    public function getJssdk()
    {
        $jssdk = $this->official_account->jssdk->buildConfig(['onMenuShareQQ','onMenuShareAppMessage','onMenuShareTimeline','onMenuShareWeibo','onMenuShareQZone'], false, $beta=false, $json=false);

        return $this->success('成功', $jssdk);
    }

    /**
     *  用户注册
     */
  	public function register()
    {
        $input = Input::all();
        //获取openid
        $_3rd_session = Redis::get($input['_3rd_session']);
        $_3rd_session = unserialize($_3rd_session);
        $insert_data = [
            'openid' => $_3rd_session['openid'],
            'name' => $input['name'],
            'sex' => $input['sex'],
            'avatar' => $input['avatar']
        ];
        $res = Member::create($insert_data);
        if($res){
            return $this->success('注册成功',['user_id'=>$res->id]);
        }else{
            return $this->error('注册失败');
        }

    }

    //获取任务列表
    public function getTask()
    {
        $input = Input::all();
        $member_info = $this->getMemberBy3rd($input['_3rd_session']);
        $result = [];
        $task_list = TaskConfig::with(['g_task_log'=>function($query) use($member_info) {
            return $query->select('id','nums','task_id')->where('member_id', $member_info['id'])->where('date', date('Y-m-d'));
        }])
            ->select('id','name','config','task_type','intro','action')
            ->orderby('id', 'asc')
            ->get()->toArray();
//        dd($task_list);
        if(!empty($task_list)) {
            //重组数据
            foreach ($task_list as $k=>$v) {
                $v['finish'] = 0;  //任务完成次数
                $v['total'] = 0;   //任务总次数
                $v['finish_money'] = 0; //任务完成任
                //务数获得金币
                $temp = unserialize($v['config']);
                $v['config'] = $temp['td'];
                preg_match('/\d+/', $v['config'][$v['finish']], $temp_money);
                $v['finish_money'] = $temp_money[0];
                if(!empty($v['g_task_log'])) {
                    $v['finish'] = $v['g_task_log'][0]['nums'] <= count($temp['td']) ? $v['g_task_log'][0]['nums'] : count($temp['td']);
                    $temp_finish_money = $v['finish'] < count($temp['td']) ? $v['config'][$v['finish']] : $v['config'][$v['finish']-1];
                    preg_match('/\d+/', $temp_finish_money, $temp_money);
                    $v['finish_money'] = $temp_money[0];
                }
                $v['total'] = count($temp['td']);

                if($v['id'] == 1) {
                    $result['t1'] = $v;
                    continue;
                }

                //每日现金任务
                if($v['id'] == 2) {
                    $my_invite = InviteLog::where('invite_id', $member_info['id'])
                        ->where('it_date', date('Y-m-d'))
                        ->orderby('id', 'asc')
                        ->take(7)->get();
                    $ids = [];
                    foreach ($my_invite as $kk=>$vv) {
                        $ids[] = $vv->binvite_id;
                    }
                    $invite_list = Member::select('id','name','avatar')
                        ->whereIn('id', $ids)
                        ->take(7)
                        ->get();
                    $v['invite_list'] = $invite_list;

                    $result['t2'] = $v;
                    continue;
                }

                if($v['id']>2 && $v['task_type'] ==0) {
                    $v['hidden'] = true;
                    $result['t3'][] = $v;
                    continue;
                }
//                if($k>1 && $v['task_type'] ==1){
//                    $v['hidden'] = true;
//                    $result['t4'][] = $v;
//                }

            }
            //试玩任务
            $task_test = TaskTest::select('id','app_id','name','intro','cash','bi')
                ->where('status',0)
                ->get();
            foreach ($task_test as $key => $val){
                $val['finish_money'] = (int)$val['bi'];
                $val['hidden'] = true;
            }
            $result['t4'] = $task_test;

        }
        //去除已完成的首次任务
        foreach ($result['t3'] as $k => $v){
            if($v['total'] == 1 && $v['finish'] == $v['total']){
                unset($result['t3'][$k]);
            }
        }
        //重新排列数组
       $result['t3'] = array_values($result['t3']);
        return $this->success('成功', $result);
    }

    //提现须知
    public function txNotice()
    {
        $info = Basic::select('id','name','keyword','value','val')->where('keyword', 'txxq')->first();

        return $this->success('成功', $info);
    }

    //访问记录
    public function getTodayLogin()
    {
        $input = Input::all();
        $member_info = $this->getMemberBy3rd($input['_3rd_session']);
        $info = (new LoginLog())->addLogin($member_info['id']);
        if($info && !empty($info)){
            return $this->success('成功', $info);
        }else{
            return $this->error('失败');
        }
    }
}
